package com.system.cacheCenterBackend.service.HotKeyService;

import com.system.cacheCenterBackend.config.HotKeyConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 热点缓存统计服务
 * 用于统计key的访问次数，当达到阈值时标记为热点数据
 */
@Service
public class HotKeyCounterService {

    @Autowired
    private HotKeyConfig hotKeyConfig;

    /**
     * key访问次数统计
     * 使用ConcurrentHashMap保证线程安全
     */
    private final ConcurrentHashMap<String, AtomicInteger> keyCounter = new ConcurrentHashMap<>();

    /**
     * 检查key是否为热点key
     *
     * @param key 缓存key
     * @return 是否为热点key
     */
    public boolean isHotKey(String key) {
        AtomicInteger counter = keyCounter.get(key);
        if (counter == null) {
            return false;
        }
        return counter.get() >= hotKeyConfig.getThreshold();
    }

    /**
     * 增加key的访问次数（异步）
     *
     * @param key 缓存key
     */
    @Async("hotKeyExecutor")
    public void incrementKeyCountAsync(String key) {
        incrementKeyCount(key);
    }

    /**
     * 增加key的访问次数
     *
     * @param key 缓存key
     * @return 当前访问次数
     */
    public int incrementKeyCount(String key) {
        AtomicInteger counter = keyCounter.computeIfAbsent(key, k -> new AtomicInteger(0));
        return counter.incrementAndGet();
    }

    /**
     * 异步重置key的访问次数
     *
     * @param key 缓存key
     */
    @Async("hotKeyExecutor")
    public void resetKeyCountAsync(String key) {
        resetKeyCount(key);
    }

    /**
     * 重置key的访问次数
     *
     * @param key 缓存key
     */
    public void resetKeyCount(String key) {
        keyCounter.remove(key);
    }

    /**
     * 获取key的访问次数
     *
     * @param key 缓存key
     * @return 访问次数
     */
    public int getKeyCount(String key) {
        AtomicInteger counter = keyCounter.get(key);
        return counter != null ? counter.get() : 0;
    }

    /**
     * 异步获取key的访问次数
     *
     * @param key 缓存key
     * @return 访问次数的CompletableFuture
     */
    @Async("hotKeyExecutor")
    public CompletableFuture<Integer> getKeyCountAsync(String key) {
        return CompletableFuture.completedFuture(getKeyCount(key));
    }

    /**
     * 获取热点key阈值
     *
     * @return 阈值
     */
    public int getHotKeyThreshold() {
        return hotKeyConfig.getThreshold();
    }

    /**
     * 重置key的访问统计
     *
     * @param key 缓存key
     */
    public void resetKeyStatistics(String key) {
        resetKeyCount(key);
    }
}